//
//  NetWorkTools.swift
//  WeiBo_One
//
//  Created by apple on 15/10/20.
//  Copyright © 2015年 蜡笔小炎. All rights reserved.
//

import UIKit
import AFNetworking

/// HTTP 网络请求枚举
enum RequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

//请求回调
typealias RequestCallBack = (result: AnyObject?, error: NSError?) -> ()

class NetWorkTools: AFHTTPSessionManager {
    //MARK: - 属性
    // app 编号
    private let appKey = "2988247405"//"3863118655"
    // app 秘钥
    private let appSecret = "d80d1586dc2f662e9249629b665ae8a8"//"b94c088ad2cdae8c3b9641852359d28c"
    // OAuth授权回调页
    let backURL = "http://itheima.com"//"http://www.baidu.com"
    
    /// 获取单例
    static let sharedTools: NetWorkTools = {
       
        let tools = NetWorkTools(baseURL: nil)

        //添加反序列化格式
        //设置反序列化数据格式 - 系统会自动将 OC 框架中的NSSet 装换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    // 获取 token 字典
    private var tokenDict: [String: AnyObject]? {
        if let token = UserAccountViewModel.sharedAccoutViewModel.accountToken {
            return ["access_token": token]
        }
        return nil
    }

}

// MARK: - 微博相关方法
extension NetWorkTools {
    
    // 加载微博
    func loadStatus(finished: RequestCallBack) {
        // token 字典为空
        guard let perems = tokenDict else {
            finished(result: nil, error: NSError(domain: "labixiaoyan_error", code: -10086, userInfo: ["message": "token 无效或为空"]))
            return
        }
        // 不为空
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 发起网络请求
        request(.GET, URLString: url, parameters: perems, finished: finished)
    }
}



//MARK: - OAuth授权相关方法
extension NetWorkTools {

    // 拼接oauth授权请求的url
    var oauthUrl: NSURL {
        //老师  https://api.weibo.com/oauth2/authorize?client_id=3863118655&redirect_uri=http://www.baidu.com
        //自己  https://api.weibo.com/oauth2/authorize?client_id=2988247405&redirect_uri=http://itheima.com
        return NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(backURL)")!
    }
    
    /// 请求获取AccessToken
    func loadAccessToken(oAuthCode code: String, finished: RequestCallBack) {
        let parameters: [String: String] = [
            "client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": backURL,]
        
        request(.POST, URLString: "https://api.weibo.com/oauth2/access_token", parameters: parameters, finished: finished)
    }

}

//MARK: - 用户相关方法
extension NetWorkTools {
    
    // 获取用户信息
    func loadAccoutInfo(accout_uid: String, accout_token: String, finished: RequestCallBack) {
        guard var parameters = tokenDict else {
            finished(result: nil, error: NSError(domain: "labixiaoyan_error", code: -10086, userInfo: ["message": "token 无效或为空"]))
            return
        }
        let url = "https://api.weibo.com/2/users/show.json"
        parameters["uid"] = accout_uid
        
        request(.GET, URLString: url, parameters: parameters , finished: finished)
    }
}


//MARK: - 封装 AFN 网络方法
extension NetWorkTools {
    
    func request(method: RequestMethod, URLString: String, parameters: [String: AnyObject], finished: RequestCallBack) {
        //成功回调
        let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            finished(result: result, error: nil)
        }
        //失败回调
        let failure = { (task: NSURLSessionDataTask, error: NSError) -> Void in
            finished(result: nil, error: error)
        }
        //根据 RequestMethod 发送网络请求
        if method == RequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        }else {
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }
    
}


